package com.wg.msshopsp.backendmanagement.shop.mapper;

import com.wg.msshopsp.backendmanagement.shop.entity.ProductSpec;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;

import java.util.List;

@Mapper
public interface ProductSpecMapper {
    // 插入规格名，并获取自增的规格ID
    @Insert("INSERT INTO productspec (product_id, spec_name) " +
            "VALUES (#{productId}, #{specName})") // #{productId}对应ProductSpec的productId字段
    @SelectKey(
            statement = "SELECT LAST_INSERT_ID()",
            keyProperty = "id", // 赋值给ProductSpec的id属性
            resultType = Long.class,
            before = false,
            statementType = StatementType.STATEMENT
    )
    void insert(ProductSpec spec);


    @Select("SELECT id AS spec_id, product_id, spec_name FROM productspec WHERE product_id = #{productId}")
    @Results({
            @Result(id = true, property = "id", column = "spec_id"), // 规格ID（唯一标识）
            @Result(property = "productId", column = "product_id"),
            @Result(property = "specName", column = "spec_name"),
            // 关联查询规格的具体值（一对多）
            @Result(
                    property = "values", // 对应 ProductSpec 中的 values 属性
                    column = "spec_id", // 传递规格ID给规格值查询
                    many = @Many(select = "com.wg.msshopsp.backendmanagement.shop.mapper.ProductSpecValueMapper.getValuesBySpecId")
            )
    })
    List<ProductSpec> getSpecsByProductId(@Param("productId") Long productId);


    // 新增：根据商品ID删除所有规格（级联删除规格值需数据库配置外键级联）
    @Delete("DELETE FROM productspec WHERE product_id = #{productId}")
    void deleteByProductId(@Param("productId") Long productId);
}

